#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import random
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.ext import db
from gaeo.controller import Controller
from application import models
import logging

class Topic(Controller):
    
    def show(self):
        self.view.forum = forum = models.Forum.get_by_permalink(self.params['permalink'])
        topic_key = 'topic|%s|%s' % (forum.permalink, self.params['topicId'])
        self.view.topic = topic = models.Topic.get_by_key_name(topic_key, parent=forum)
        
        self.view.replies = models.Reply.get_replies_by_topic(topic)
        self.view.page_title = '%s &laquo; %s &laquo; Taipei GTUG Forum' % (topic.title, forum.title)
    
    def create(self):
        try:
            result = {'ok': True}
            
            post = self.params.get('post')
            
            # get forum key
            forum_key = post['forum']
            forum = models.Forum.get(forum_key)
            
            # get user
            user = self.view.member
            
            # get counter
            shared_index = random.randint(0, 7)
            counter_key_name = 'counter|topics|%s|%d' % (forum.permalink, shared_index)
            counter = models.Counter.get_or_insert(counter_key_name,
                                                   parent=forum,
                                                   name='%s_topics' % forum.permalink)
            # create topic
            serial = models.ForumSerial.get_or_insert("topic|%s" % forum.permalink)
            val = serial.value
            topic = models.Topic(key_name="topic|%s|%d" % (forum.permalink, val),
                                 forum=forum,
                                 parent=forum,
                                 author=user,
                                 title=post['title'],
                                 description=db.Text(post['desc']),
                                 serial=serial.value)
            topic.put()
            serial.value += 1
            serial.put()
            
            # counter + 1
            counter.value += 1
            counter.put()
            
            # update user post count            
            cache_key = 'posts_count|%s' % user.name
            count = memcache.get(cache_key)
            if count is not None:
                memcache.incr(cache_key)
            
            cache_key = 'topics_count|%s' % forum.permalink
            count = memcache.get(cache_key)
            if count is not None:
                memcache.incr(cache_key)
            
            cache_key = 'forum|%s|topics' % forum.permalink
            memcache.delete(cache_key)

            result.update({
                'topicId': val,
                'forumLink': forum.permalink
            })
        except Exception, e:
            result = {'ok': False, 'msg': 'Reason: %s' % e}
        
        if self.is_xhr:
            self.json_output(result)
            
    def reply(self):
        import re
        from gaeo.utils import safeout
        try:
            result = {'ok': True}
            
            forum = models.Forum.get(self.params['forum'])
            topic = models.Topic.get_by_key_name('topic|%s|%s' % (forum.permalink, self.params['topic']),
                                                 parent=forum)

            # get user
            user = self.view.member
            
            content = self.params['content']
            # TODO: pre-process content
            
            # get counter
            shared_index = random.randint(0, 7)
            pair = (forum.permalink, topic.serial)
            counter_key_name = 'counter|replies|%s|%d|%d' % (forum.permalink, topic.serial, shared_index)
            counter = models.Counter.get_or_insert(counter_key_name,
                                                   parent=forum,
                                                   name='%s_%d_replies' % pair)
            
            # create topic
            serial = models.ForumSerial.get_or_insert("replies|%s|%d" % pair)
            reply = models.Reply(key_name="reply|%s|%d|%d" % (forum.permalink, topic.serial, serial.value),
                                topic=topic,
                                parent=topic,
                                floor=serial.value,
                                author=user,
                                content=db.Text(content))
            reply.put()
            serial.value += 1
            serial.put()

            # counter + 1
            counter.value += 1
            counter.put()
            
            cache_key = 'replies_count|%s|%d' % pair
            count = memcache.get(cache_key)
            if count is not None:
                memcache.incr(cache_key)
            
            cache_key = 'topic_%s_replies' % (topic.key())
            memcache.delete(cache_key)
            
            # update topic
            topic.last_replied = user
            topic.put()
            
            result.update({
                'replyId': reply.floor,
                'content': safeout(content),
                'time': reply.replied.strftime('%Y-%m-%d %H:%M:%S')
            })

        except Exception, e:
            logging.error(e)
            result = {'ok': False, 'msg': 'Reason: %s' % e}
            
        if self.is_xhr:
            self.json_output(result)